package cn.edu.hzw.comic.mvp.view

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import cn.edu.hzw.comic.R
import cn.edu.hzw.comic.mvp.model.Page
import cn.edu.hzw.comic.mvp.presenter.PagePresenter
import kotlinx.android.synthetic.main.activity_pager.*
import org.jetbrains.anko.async
import org.jetbrains.anko.uiThread

class PagerActivity : AppCompatActivity() {
    companion object{
        val INTENT_LINK = "link"
    }
    lateinit var link:String
    var mDate = ArrayList<Page>()
    lateinit var adapter: PageAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pager)
        init()
    }

    override fun onResume() {
        super.onResume()
        async(){
            val data = PagePresenter().obtain(link)
            mDate = data
            uiThread {
                adapter.refreshData(data)
            }
        }
    }
    private fun init(){
        link = intent.getStringExtra(INTENT_LINK)!!
        adapter = PageAdapter(mDate,supportFragmentManager)
        viewPager.adapter = adapter
        viewPager.offscreenPageLimit = 2
    }
    class PageAdapter(var data:ArrayList<Page> = ArrayList<Page>(),fragmentManager: FragmentManager)
        :FragmentPagerAdapter(fragmentManager){
        override fun getCount(): Int = data.size

        override fun getItem(position: Int): Fragment = newInstance(data[position].link)
        fun refreshData(newData:ArrayList<Page>){
            data = newData
            notifyDataSetChanged()
        }
        fun newInstance(link:String) = PageFragment(link)

    }
}